<template>
  <div class="mian-page">
    <div class="page-title">
      {{ route.meta.title }}
    </div>
    <div class="page-sub-title">专注于表格的使用</div>
    <div class="page-search">
      <el-button type="primary" @click="show = true">新增</el-button>
    </div>
    <el-table :data="rowData" empty-text="暂无数据">
      <el-table-column prop="date" label="uuid" width="180" />
      <el-table-column prop="name" label="Name" width="180" />
      <el-table-column prop="address" label="Address" />
      <el-table-column prop="label" label="Label" width="180" />
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button type="primary" size="mini" @click="handleEdit(scope.row)"
            >编辑</el-button
          >
          <el-button type="danger" size="mini" @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <UserForm
      v-if="show"
      v-model:visible="show"
      @close="close"
      :form="form"
      @submit="submit"
    />
    <HModel v-model:open="openModel" @update:open="updateOpenModel" />
  </div>
</template>

<!-- 顶层 setup 逻辑 -->
<script setup lang="ts">
import { ref } from "vue";
import { useRoute } from "vue-router";
import { getUsers } from "@/api/user";
import UserForm from "./UserForm.vue";
import HModel from "@/components/HModel.vue";

const route = useRoute();
const show = ref(false);
const form = ref<{
  name: string;
  id: string;
}>({
  name: "",
  id: "",
});

const rowData = ref<
  {
    name: string;
    id: string;
  }[]
>([
  {
    name: "张三",
    id: "123456",
  },
  {
    name: "李四",
    id: "654321",
  },
]);

const openModel = ref(false);

onMounted(() => {
  getUsers().then((res) => {
    console.log("getuser-res", res);
    // rowData.value = res.data;
  });
});

/**
 * 编辑用户
 * @param row 用户信息
 */
const handleEdit = (row: { name: string; id: string }) => {
  show.value = true;
  form.value = row;
  console.log("edit", row);
};

const close = () => {
  show.value = false;
  form.value = {
    name: "",
    id: "",
  };
};

/**
 * 提交表单
 * @param row 用户信息
 */
const submit = (row: { name: string; id: string }, isEdit: boolean) => {
  console.log("submit", row, isEdit);
  if (row.id) {
    // 编辑用户
    rowData.value = rowData.value.map((item) => {
      if (item.id === row.id) {
        return row;
      }
      return item;
    });
  } else {
    // 新增用户
    rowData.value.push(row);
  }
  close();
};

/**
 * 删除用户
 * @param row 用户信息
 */
const handleDelete = (row: { name: string; id: string }) => {
  console.log("delete", row);
  openModel.value = true;
  form.value = row;
};

const updateOpenModel = (val: boolean) => {
  if (val) {
    // 确认删除
    rowData.value = rowData.value.filter((item) => item.id !== form.value.id);
  }
  openModel.value = false;
};
</script>

<!-- 声明组件名称 -->
<script lang="ts">
export default {
  name: "User", // 定义组件名称为 User
};
</script>
